function Core(){
	this.url = null;
	this.params = null;
	this.locale = "zh_CN";
}
Core.extend = function(subFn, superFn) 
{
	subFn.prototype = new superFn();
	subFn.prototype.constructor = subFn;
	var p = subFn.prototype;
	if (subFn.overrides)
	 {
	 		
		for ( var method in subFn.overrides)
		 {
			p[method] = subFn.overrides[method];
		}
		delete subFn.overrides;
	}
	if (subFn.extend) {
		for ( var method in subFn.extend) {
			p[method] = subFn.extend[method];
		}
		delete subFn.extend;
	}
};
Core.prototype.language="zh_CN";//en
//sem
Core.prefix="http://"+window.location.hostname + ":" + location.port + "/api";
//report
Core.reportprefix='http://'+window.location.hostname + ":" + location.port + '/report/api';
//crabman
Core.crabmanprefix='http://'+window.location.hostname + ":" + location.port + '/newcrabman/api';
// nerd
//Core.nerdprefix='http://192.168.0.132/nerd/api';
Core.nerdprefix='http://'+window.location.hostname + ":" + location.port + '/nerd_new/api';
//Core.nerdprefix='http://192.168.0.132/nerd/api';
Core.nerdprefix='http://'+window.location.hostname + ":" + location.port +'/nerd/api';
//ads-email
Core.emailprefix='http://'+window.location.hostname + ":" + location.port +'/email/api';

//tracking
Core.tracking="http://"+window.location.hostname + ":" + location.port + "/tracking/api";
Core.trackingprefix="http://"+window.location.hostname + ":" + location.port +"/tracking";
//local
Core.rootprefix = "http://"+window.location.hostname + ":" + location.port;

//suffix
Core.suffix = ".json";
//menu的数据
Core.global = null;
//选项卡的索引
Core.tabIndex = null;
//投资组合Id
Core.portfolioId = null;
//report --  next run report time field
Core.timeer = null;
Core.timeerTodo = null;
Core.indexAnalysis=['BAIDU','BAIDU','BAIDU','BAIDU','BAIDU','BAIDU'];
Core.domainAnalysis=['BAIDU','BAIDU','BAIDU','BAIDU','BAIDU','BAIDU'];
//toolkit
Core.timerForEvent=null;
Core.timerForRealTime=null;
Core.timerForKeyword=null;
Core.timerForKeywordEstimate=null;
//广告商id
Core.advertiseId=null;
//投资组合Id
Core.portfolioId=null;
//广告用户的Id
Core.accountId=null;
//系列Id
Core.campaignId=null;
//广告组Id
Core.adgroupId=null;

//广告id
Core.adId=null;
//平台
Core.network=null;
//屏幕高度
Core.screenHeight=$(window).height();
//操作的id
Core.opreateId=null;

//优化关键字的数据
Core.optimizeKeywords=null;
//用于判断监控或广告级别下的  批量文本替换
Core.textReplaceType=null;
//缓存数据
Core.catchData={};
//是否全选
Core.selectAll={};
//adgroup替换类型
Core.typeReplace=null;
//keyword替换类型
Core.keyReplace=null;


//create params
Core.createParam = function(networkType,params) {
	var jsonParams = {};
	for(var field in params) {
		jsonParams[field] = params[field];
	}
	//添加固定参数
	return {"locale": "zh_CN", "network": networkType==null?"GOOGLE":networkType, "params": jsonParams};
};

//create url
Core.createUrl = function(url,webtype) {
	//添加固定参数
	if(webtype=="report"){
		return Core.reportprefix  + url + Core.suffix;
	}else if(webtype=="crabman"){
		return Core.crabmanprefix+ url+Core.suffix;
	}else if(webtype=="email"){
		return Core.emailprefix+ url+Core.suffix;
	}
	else if(webtype=="nerd"){
		return Core.nerdprefix+ url+Core.suffix;
	}
	else if(webtype=="tracking"){
		return Core.tracking+ url+Core.suffix;
	}else if(webtype=="root"){
		return 	Core.rootprefix + url ;
	}
	return Core.prefix  + url + Core.suffix;
};

//choose Type
Core.chooseType = function(type){
	var ajaxType=type==null?"json":type;
	return ajaxType;
};

//TODO will be replace while refactor
Core.showErrorMessage=function(div,message){
	//alert(message);
	$.jBox.tip(message,message_type);	
};

Core.inputTips=function(){
        $(".inputtips").remove()
        var tar = $("input[inputtips]")
 
        $("input[inputtips],textarea[inputtips]").each(function(index,item){
            $(this).before("<label class='inputtips' style='color:#8B9096;cursor:text' for='" + $(this).attr("id") + "'>" + $(this).attr("inputtips") + "</label>")
            $(this).prev("label").css({
                position: "absolute",
                margin: "3px 0 0 10px",
                zIndex: "1"
            })
            $(this).prev("label").attr("style", $(this).prev("label").attr("style") +";"+ $(this).attr("tipstyle"))
             if ($(this).val() == "") {
                        $(this).prev("label").css("display","")
                    }
                    else {
                        $(this).prev("label").hide()
                    }
            $(this).focus(function(){
                var tar = $(this)
                $(this).prev("label").stop().animate({
                    opacity: 0.4
                }, 300);
            }).blur(function(){
                $(this).prev("label").stop().animate({
                    opacity: 1
                }, 300);
            })
			item.oninput=item.onchange=item.onpropertychange=function(o){    
     			if ($(this).val() == "") {
                    $(this).prev("label").css("display","")
                }
                else {
                    $(this).prev("label").hide()
                }   
 			};    
        })
		$("input[onenter]").unbind("keypress").bind("keypress",function(e){
				if(e.keyCode==13){
					$("#"+$(this).attr("onenter")).click()
					return false
				}
			})
		$("textarea[onenter]").unbind("keypress").bind("keypress",function(e){
				if(e.keyCode==10){
					$("#"+$(this).attr("onenter")).click()
					return false
				}
		})
        $(".inputtips").unbind().bind("click", function(){
            $(this).next("input").focus()
        })
}
Core.inputMax=function(){
	var len = function(e)
			{ 
			    return e.replace(/[^\x00-\xff]/g, "xx").length; 
			} 
	var limitDo=function(limit){
	    var val=this.value;
	    if(len(val)>limit) {
	        while(len(val=val.substr(0,val.length-1))>limit);
	        this.value=val;
	    }
	}
		$(".maxtip").remove()
        $("input[maxlength]").each(function(){
			if(typeof($(this).attr("nonum"))=="undefined")
			{$(this).after("<span class='maxtip'>"+len($(this).val())+"/"+$(this).attr("maxlength")+"</span>")}
		}).keyup(function(){
			limitDo.call(this,$(this).attr("maxlength"))
			if(typeof($(this).attr("nonum"))=="undefined"){
				$(this).next(".maxtip").text(len($(this).val())+"/"+$(this).attr("maxlength"))
				}
		})/*.change(function(){
			$(this).next(".maxtip").text(len($(this).val())+"/"+$(this).attr("maxlength"))
		})*/
		
}
Core.getInputMaxLength=function(inputValue){
	  return inputValue.replace(/[^\x00-\xff]/g, "xx").length; 
}
Core.createDate=function(str){
        str = str.split(' ');
		var date=str[0].split("-")
		var time=str[1].split(":")
        var newdate = new Date();
        newdate.setUTCFullYear(date[0], date[1] - 1, date[2]);
        newdate.setUTCHours(time[0], time[1], time[2], 0);
        return newdate;
    }
Core.addTrackingDelegate=function(actionObj)
{
	if(actionObj.webtype=='tracking')
	{
		var tkurl=Core.tracking+actionObj.url;//save tracking target url
		actionObj.url="/tracking/delegate";//set the fixed target delegate url in sem
		actionObj.webtype='sem';//send request to sem
		actionObj.params.tkurl=tkurl;//set tkulr as tracking target url
		if(typeof(actionObj.params.tokentype)=='undefined')
		{
			actionObj.params.token=Core.tk_tokenAuth;
		}
		
	}
}
//ajax method
Core.ajax = function(actionObj) {
	var options = {
			type: "POST",
			url: Core.createUrl(actionObj.url,actionObj.webtype),
			data: $.toJSON(Core.createParam(actionObj.network,actionObj.params)),
			dataType: Core.chooseType(actionObj.dataType),
			async:actionObj.async==null?true:false,
			beforeSend:actionObj.beforeSend,
			complete:actionObj.complete,
			success:function(data){
				if(data.error){
					code=data.error.code;
					//将code和session过期返回的字符串对比
					if(code=="INVALID_USER"){
						//如果code为INVALID_AUTH那么session过期了,跳到登陆页面
						window.location.href = "../login.html";
						return ;
					}
				}
				
				actionObj.success(data);
			},
			error: function(data,status){
				actionObj.error&&actionObj.error(data,status);
			}
	};
	if(actionObj.AjaxManager){
		!$.AjaxManager.getQueue(actionObj.AjaxManager.nameSpace)&&$.AjaxManager.createQueue(actionObj.AjaxManager.nameSpace, actionObj.AjaxManager.override);
		 $.AjaxManager.getQueue(actionObj.AjaxManager.nameSpace).offer(options);
	}else{
		$.ajax(options); 
	}
};

/**
*显示列表的ajax
*@author shanghongliang
*@date 2011年11月18日14:22:29
*@param{Object} actionObj ajax的各种参数对象，
*@param{String} targetId 如果有错误,错误的目标id
*@param{String} mess 如果没有返回结果，显示的文本提示信息 
*@param{function} callback 执行完该方法后需要执行的方法
*/
Core.listAjax=function(actionObj,targetId,mess,callback){
	var action=actionObj;
	action.beforeSend=function(){
		$("#"+targetId).hide();
		$("#"+targetId+"_loading_img").show();
	}
	action.success=function(data){
		var message=Core.checkDataFromResult(data);
		$("#"+targetId).show();
		$("#"+targetId+"_loading_img").hide();
		if(message&&message!="result"){
			$("#"+targetId).html("<div style='text-align:center; padding:20px;'>"+message+"</div>");
			if(callback&& typeof callback){
				callback();
			}
			return;
		}
		if(message=="result"){
			$("#"+targetId).html("<div style='text-align:center; padding:20px;'>"+mess+"</div>");
			//return;
		}
		actionObj.sus(data);
	}
	action.error=function(data,status){
		if(status=="error"){
			$("#"+targetId).show();
			$("#"+targetId+"_loading_img").hide();
			$("#"+targetId).html("<div style='text-align:center; padding:20px;'>"+message_content_web_error+"</div>");
		}
		actionObj.err();
	}
	Core.ajax(action);
}



/**
*操作的ajax操作
*@description 在添加之类的操作会用到
*@author shanhongliang
*@date 2011年11月18日17:36:24
*@param{Object} actionObj ajax的各种参数对象，
*@param{String} mess_success 操作成功,显示的文本提示信息
*@param{String} mess_error 操作失败,显示的文本提示信息
*@param{Boolean} freeze 在提交请求是否锁住页面
*@param{String} tipType 提示类型（区分是tip还是confirm）
*/
Core.operateAjax=function(actionObj,mess_success,mess_error,freeze,tipType,callback){
	var action=actionObj;
	action.success=function(data){
		var message=Core.checkDataFromResult(data);
		if(message&&message!="result"){
			$.jBox.tip(message,'info');
			return;
		}
		if(data.result){
			$.jBox.closeTip();
			Core.opreateId=data.result.id;
			if(tipType=="confirm"&&callback&&typeof callback ==　"function"){
				$.jBox.confirm(mess_success,message_title_info,callback);
			}else{
				$.jBox.tip(mess_success,'success');
			}
		}else{
			$.jBox.tip(mess_error,'error');
		}
		actionObj.sus(data);
	}
	if(freeze){
		action.beforeSend=function(){
			$.jBox.tip(message_content_loading, 'loading');
		}
	}
	action.error=function(){
		$.jBox.tip(message_content_web_error,'error');
		actionObj.err();
	}
	Core.ajax(action);
}




Core.ajax2 = function(actionObj) {
	$.ajax({
		type: "POST",
		url: Core.createUrl(actionObj.url,actionObj.webtype),
		data: $.toJSON(Core.createParam(actionObj.network,actionObj.params)),
		dataType: Core.chooseType(actionObj.dataType),
		async:actionObj.async==null?true:false,
		beforeSend:actionObj.beforeSend,
		complete:actionObj.complete,
		success:function(data){
			if(data.error){
				code=data.error.code;
				//将code和session过期返回的字符串对比
				if(code=="INVALID_USER"){
					//如果code为INVALID_AUTH那么session过期了,跳到登陆页面
					window.location.href = "../login.html";
					return ;
				}
			}
			actionObj.success(data);
		},
		error: function(){
			actionObj.error;
		}
	});
};


Core.ajax_logout = function(actionObj) {
	$.ajax({
		type: "POST",
		url: Core.createUrl(actionObj.url,actionObj.webtype),
		data: $.toJSON(Core.createParam(actionObj.network,actionObj.params)),
		dataType: Core.chooseType(actionObj.dataType),
		async:actionObj.async==null?true:false,
		beforeSend:actionObj.beforeSend,
		complete:actionObj.complete,
		success:function(data){
			if(data.error){
				code=data.error.code;
				if(code=="INVALID_USER"){
					window.location.href = "../login.html";
					return ;
				}
			}
			actionObj.success(data);
		},
		error: actionObj.error
	});
};


Core.redXml=function(actionObj){
	$.ajax({
		type: "POST",
		url: actionObj.url,
		data: "",
		dataType: "xml",
		//async: false,
		success: actionObj.success,
		error: actionObj.error
	});
}

//错误信息
Core.dataError=function(targetId,message){
	var ele=$("#"+targetId);
	ele.html("");
	var mess=$("<div id='error_message'>"+message+"</div>");
	mess.appendTo(ele);
	
}

/**
*function 对返回的数据进行检验（对用户过期需要跳转到登陆页面），并返回结果
*use 调用这个方法时将后台返回的数据传递过来，如果数据有问题的话，
*该方法将返回对应的提示信息，如果没有问题的话，将返回空字符串
*date 2011年6月1日13:48:32
*by shanghongliang
*/
Core.checkDataFromResult=function(json){
	var message="";
	var code="";
	if(!json ){
		 message="系统数据错误，请稍后重试！";	
		 return message;
	}

	//如果errorcode里面有
	if(json.error){
		code=json.error.code;
		//将code和session过期返回的字符串对比
		if(code=="INVALID_USER"){
			//如果code为INVALID_AUTH那么session过期了,跳到登陆页面
			window.location.href = "../login.html";
		}else if(code=="INVALID_AUTH"){
			message="没有权限";
			return message;
		}else{
			message=json.error.message;
			return message;
		}
		return ;
	}
	
	if(null==json.result){
		message="系统错误！";	
		return message;
	}
	
	//如果返回的是result，该方法将放回result字符，使用高方法之后对比返回的值然后进行操作
	if(json.result.length==0 || json.result==false || (json.result.data!=null && (json.result.data.length==0 || json.result.data==false))){
		message="result";
		return message;
	}
	return "";
}

Core.messageTip=function(title,message,disappear,callback){
	var length=arguments.length;
	var argumArray=arguments;
	if($("#errorPop_show_dialog").length==0){
		var box="<div class='pop_box grey_pop alert_g_pop mod_g_pop' id='errorPop_show_dialog' style='display: none;'>"
    	+"<div class='pop_con'>"
		+"<div class='pop_detail bgc_fff'>"
        +"<div class='detail error' style='font-size:14px;font-weight:bold; '>"
        +"<div id='errorPop_show_message'></div>"
        +"</div>"
		+"<div class='ver_max_h;' style='height: 100px;'>"
        +"</div>"
        +"</div>"
		+"<div class='subm'  style='background-color: #FFF; border: none;'>"
        +"<a href='javaScript:void(0)' onclick='$.unblockUI(); return false;' class='btn_lb_sm'><span>确定</span></a>"
        +"</div>"
		+"</div>"
    	+"<a href='javaScript:void(0)' onclick='$.unblockUI(); return false;' class='close_pop' title='关闭'>X</a>"
    	+"<div style='position: absolute; left: 12px; top: 10px; color:#ffffff;font-weight: bold;' id='errorPop_show_title' >Error</div>"
		+"</div>";
		$("#body").append(box);
	}
	$("#errorPop_show_title").text(title);
	$("#errorPop_show_message").text(message);
	
	$.blockUI({message:$("#errorPop_show_dialog"), css : {width:"380px", height:"200px", top:"50%", left:"50%", margin:"-100px 0 0 -190px", border:"0 none", background:"transparent", textAlign:"left", cursor:"default"},overlayCSS:{backgroundColor : '#fff'}});
	if(disappear){
		setTimeout(function(){
			$("#errorPop_show_dialog").find("a.close_pop").trigger("click");
		},2500);
	}
}


//显示对话框
Core.messageTipDialog=function(title,message,divwidth,divheight,callback){
	var length=arguments.length;
	var argumArray=arguments;
	$("#show_dialog").find(".show_dialog_title").html(title);
	$("#show_dialog").find(".show_dialog_message").html(message);
	var screenHeight=$(document).height();
	var screenWidth=$(document).width();
	if(screenHeight<400){
		screenHeight=400;
	}else{
		screenHeight=screenHeight-200-screenHeight*0.25;
	}
	if(screenWidth<600){
		screenWidth=600;
	}else{
		screenWidth=screenWidth-screenWidth*0.4;
	}
	
	var height=screenHeight+"px";
	var width=screenWidth+"px";
	var margin_left=(screenWidth/2)+"px";
	if(divwidth&&divheight){
		height=divheight;
		width=divwidth;
		margin_left=(parseInt(width)/2)+"px";
	}
	$.blockUI({message:$("#show_dialog"), css : {width:width, height:height, top:"5%", left:"50%", margin:"0px 0 0 -"+margin_left, border:"0 none", background:"transparent", textAlign:"left", cursor:"default"},overlayCSS:{backgroundColor : '#fff'}});
	$(".mi_operat_box").find(".mi_o_main").find(".placeholder").text("");
	$("#show_dialog").find("button.btn_s_b").unbind("click");
	$("#show_dialog").find("button.btn_s_b").bind("click",function(e){
		$.unblockUI();
		if(callback&&typeof callback=="function"){
			if(length==5){
				var arum4=argumArray[3];
				var arum5=argumArray[4];
				callback(arum4,arum5);
			}
		}								 
	});
	$("#show_dialog").find("a.close").unbind("click");
	$("#show_dialog").find("a.close").bind("click",function(e){
		$.unblockUI();
		if(callback&&typeof callback=="function"){
			if(length==5){
				var arum4=argumArray[3];
				var arum5=argumArray[4];
				callback(arum4,arum5);	
			}
		}										 
	});
}

/** 
* window.onresize 事件 专用事件绑定器 v0.1 Alucelx 
* <description> 
* 用于解决 lte ie8 & chrome 及其他可能会出现的 原生 window.resize 事件多次执行的 BUG. 
* </description> 
* <methods> 
* add: 添加事件句柄 
* remove: 删除事件句柄 
* </methods> 
*/ 
Core.onWindowResize = function(){ 

var queue = [], 
indexOf = Array.prototype.indexOf || function(){ 
var i = 0, length = this.length; 
for( ; i < length; i++ ){ 
if(this[i] === arguments[0]){ 
return i; 
} 
} 
return -1; 
}; 
var isResizing = {},
lazy = true,
listener = function(e){ 
var h = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight, 
w = window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || document.body.clientWidth; 
if( h === isResizing.h && w === isResizing.w){ 
return; 
}else{ 
e = e || window.event; 
var i = 0, len = queue.length; 
for( ; i < len; i++){ 
queue[i].call(this, e); 
} 
isResizing.h = h, 
isResizing.w = w; 
} 
} 
return { 
add: function(fn){ 
if(typeof fn === 'function'){ 
if(lazy){ 
if(window.addEventListener){ 
window.addEventListener('resize', listener, false); 
}else{ 
window.attachEvent('onresize', listener); 
} 
lazy = false; 
}
	queue.push(fn);
}else{ } 
return this; 
}, 
remove: function(fn){ 
if(typeof fn === 'undefined'){ 
queue = []; 
}else if(typeof fn === 'function'){ 
var i = indexOf.call(queue, fn); 
if(i > -1){ 
queue.splice(i, 1); 
} 
} 
return this; 
} 
}; 
}.call(this);  
Core.showTheDialog=function(width,height){
	var w=width/2;
	var h=height/2;
	$.blockUI({message:$("#pop_up_dialog"), css : {width:width+"px", height:height+"px", top:"50%", left:"50%", margin:"-"+h+"px 0 0 -"+w+"px", border:"0 none", background:"transparent", textAlign:"left", cursor:"default"},overlayCSS:{backgroundColor : '#fff'}});
}

/**
*function 弹出对话框 
*date 2011年7月8日9:04:51
*by shanghongliang
*/
Core.ajaxShowDialog = function(actionObj) {
	$.ajax({
		type: "POST",
		url: Core.createUrl(actionObj.url,'sem'),
		data: $.toJSON(Core.createParam(actionObj.networkType,actionObj.params)),
		dataType: "json",
		beforeSend:function(){
		},
		complete:function(){
			
		},
		//async: false,
		success:function(data){
			var message=Core.checkDataFromResult(data);
			if(message!=""){
				Core.messageTip("信息提示",message);
				//clearInterval(Core.timeerNetScreen);
				return;
			}
			if(data.result){
				if(data.result.data){
					if($("#dataLoading").length){
						if(actionObj.before){
							var before=	actionObj.before;
							var targetId=before.targetId;
							if($("#dataLoading").length>0){
								$("#dataLoading").remove();
							}
						}
					}
				}else{
					return;
				}
			}
			if(data.error){
				code=data.error.code;
				//将code和session过期返回的字符串对比
				if(code=="INVALID_USER"){
					//如果code为INVALID_AUTH那么session过期了,跳到登陆页面
					window.location.href = "../login.html";
				}else if(code=="INVALID_AUTH"){
					message="没有权限";
					return message;
				}else{
					message=data.error.message;
					return message;
				}
				return ;
			}
			actionObj.success(data);
		},
		error: actionObj.error,
		operatingObjs: actionObj.operatingObjs
	});
};
